import socket
import _thread
import time

open_the_doors = set()

def server(s:socket.socket):
    while True:
        data, addr = s.recvfrom(1024)
        tmp_info = (data.decode()).split('$&')
        print('Receive({}):{}'.format(addr,tmp_info))
        if tmp_info[0] == 'addrs':
            addrs = eval(tmp_info[1])
            for addr_str in addrs:
                if addr_str not in open_the_doors:
                    open_the_doors.add(addr_str)
                    tmp_addr = addr_str.split(':')
                    _thread.start_new_thread(client, (s, socket.gethostname(),
                                                      (tmp_addr[0], int(tmp_addr[1]))
                                                      )
                                             )




def client(s, info:str, addr:tuple, t=5):
    while True:
        print('send:{} \n to:{}'.format(info, addr))
        s.sendto(info.encode(), addr)
        time.sleep(t)


if __name__ == '__main__':
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip = '0.0.0.0'
    s.bind((ip, 8000))
    _thread.start_new_thread(server, (s,))
    _thread.start_new_thread(client, (s, socket.gethostname(), ('49.234.223.76', 8000), 10))
    print("asd")
